package com.example.petproject.service.third.ali;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.example.petproject.config.AliYunSmsConfig;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 包名称：com.example.petproject.service.third.ali
 * 类名称：AliYunSmsService
 * 类描述：阿里云短信服务层
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月04日 14:50
 **/
@Service
public class AliYunSmsService {

    private static final Logger log = LoggerFactory.getLogger(AliYunSmsService.class);

    @Resource
    private AliYunSmsConfig aliYunSmsConfig;

    /**
     * 整个系统中通用型的短信发送
     *
     * @param phoneNumber   发送手机号
     * @param templateCode  模版名
     * @param templateParam 模版参数，必须为json格式的字符串
     * @return 短信发送的结果成功为true,失败为false
     */
    public Boolean sendSms(String phoneNumber, String templateCode, String templateParam) {
        log.info("发送短信,手机号:{},模版:{},模版参数:{}", phoneNumber, templateCode, templateParam);
        //封装客户端配置，主要是全局的配置项
        Config config = new Config()
                .setAccessKeyId(aliYunSmsConfig.getAccessKeyId())
                .setAccessKeySecret(aliYunSmsConfig.getAccessKeySecret())
                .setEndpoint(aliYunSmsConfig.getEndpoint());
        try {
            //初始化短信发送客户端
            Client client = new Client(config);
            //初始化每一个短信发送请求参数
            SendSmsRequest request = new SendSmsRequest()
                    //手机号
                    .setPhoneNumbers(phoneNumber)
                    //签名
                    .setSignName(aliYunSmsConfig.getSignName())
                    //模版编码
                    .setTemplateCode(templateCode)
                    //模版参数
                    .setTemplateParam(templateParam);
            //发起请求调用API
            SendSmsResponse response = client.sendSms(request);
            if (!response.body.code.equals("OK")) {
                log.warn("短信发生失败，{},{}", response.body.code, response.body.message);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("短信发生异常：{}",e.getMessage());
            return false;
        }
    }

}
